package com.cyzy.config;

import com.alibaba.fastjson.JSON;
import com.cyzy.utils.RedisUtil;
import com.cyzy.utils.SpringContextUtil;
import jakarta.websocket.HandshakeResponse;
import jakarta.websocket.server.HandshakeRequest;
import jakarta.websocket.server.ServerEndpointConfig;

import java.util.List;
import java.util.Map;

/**
 * @author cuncun
 * @create 2025-06-05 下午2:44
 */
public class GetHttpSessionConfiguratorS extends ServerEndpointConfig.Configurator {

    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response){
        RedisUtil redisUtil = SpringContextUtil.getBean(RedisUtil.class);
        Map<String, List<String>> headers = request.getHeaders();

        System.out.println(headers + " -----headers");
        //从 "Token" 请求头中提取用户在redis中的key值  token=123456
        List<String> TokenList = headers.get("Token");
        String token = TokenList.get(0);
        //sender_type 请求头中提取发送方的类型
        List<String> senderTypeList = headers.get("sender_type");
        String senderType = senderTypeList.get(0);
        System.out.println(senderType);
        //如果没有token直接结束
        if(TokenList == null){
            System.out.println("没有携带token");
            return;
        }
        //查看用户是否有登陆
        String tokens = redisUtil.get(token);
        Map<String,Object> user = JSON.parseObject(tokens);
        System.out.println(user + " 用户信息");
        //如果用户不存在
        if(user == null){
            System.out.println("redis没有查到用户登录信息!");
            return;
        }
        sec.getUserProperties().put("userId",senderType + user.get("id"));
    }
}
